<template>
  <div class="app-container">
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wrapper">
        <el-form
          :inline="true"
          :model="selUserListQuery"
          class="demo-form-inline"
        >
          <el-form-item label="真实名称:">
            <el-input
              v-model="selUserListQuery.name"
              clearable
              placeholder="请输入真实名称"
            />
          </el-form-item>
          <el-form-item label="所属角色:">
            <el-select
              v-model="selUserListQuery.role"
              placeholder="请选择角色"
              clearable
              @change="handleRoleChange"
            >
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属部门:">
            <el-select
              v-model="selUserListQuery.department"
              clearable
              placeholder="请选择部门"
              @change="handleDepartmentsChange"
            >
              <el-option
                v-for="item in departmentList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-collapse-transition>
    <el-card>
      <!-- <div slot="header"></div> -->
      <div>
        <!-- 操作按钮区域 -->
        <div class="table-operations">
          <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
          >{{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            />
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="dialogVisible = true"
          >新建</el-button>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            @click="handleDeleteClick"
          >批量删除</el-button>
          <!-- <el-dropdown style="float: right">
            <el-button size="small">
              更多操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>导入</el-dropdown-item>
              <el-dropdown-item>导出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown> -->
        </div>

        <!-- 表格区域 -->
        <el-table
          v-loading="loading"
          :data="selUserLists"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            type="index"
            label="序号"
            width="60"
          />
          <el-table-column prop="name" label="账户名称" />
          <el-table-column prop="loginName" label="登录账号" />
          <el-table-column prop="role" label="所属角色" />
          <el-table-column prop="department" label="所属部门" />
          <!-- <el-table-column prop="createTime" label="创建时间" width="180">
            <template slot-scope="scope">
              {{ formatCreateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" width="180">
            <template slot-scope="scope">
              {{ formatCreateTime(scope.row.updateTime) }}
            </template>
          </el-table-column> -->
          <el-table-column label="操作" width="150" align="center">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
              >编辑</el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-row :gutter="10" style="margin-top: 20px" type="flex" justify="end">
        <el-pagination
          background
          :current-page="currentPage4"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="formData.id ? '编辑' : '新增'"
      :visible.sync="dialogVisible"
      width="800px"
      @close="close"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-position="top"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="真实姓名:" prop="name">
              <el-input v-model="formData.name" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账户名称:" prop="loginName">
              <el-input
                v-model="formData.loginName"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属部门:" prop="departmentId">
              <el-select
                v-model="formData.departmentId"
                placeholder="请选择"
                style="width: 100%"
                clearable
                @change="handleDepartmentChange"
              >
                <el-option
                  v-for="item in departmentList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话:" prop="mobile">
              <el-input
                v-model="formData.mobile"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="formData.id" :gutter="20">
          <el-col :span="12">
            <el-form-item label="密码:" prop="password">
              <el-input
                v-model="formData.password"
                :type="passwordVisible ? 'text' : 'password'"
                placeholder="请输入新密码，不修改请留空"
              >
                <i
                  slot="suffix"
                  class="el-icon-view password-eye"
                  @click="passwordVisible = !passwordVisible"
                />
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="角色:" prop="roleId">
              <el-checkbox-group v-model="formData.roleId" class="role-list">
                <el-checkbox
                  v-for="role in roleList"
                  :key="role.id"
                  :label="role.id"
                >
                  {{ role.name }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selUserListApi,
  addUserApi,
  delUserByIdApi,
  selRoleListApi,
  selDepartmentListApi,
  selUserByIdApi,
  updateUserByIdApi
} from '@/api/system'
export default {
  name: 'UserManagement',
  data() {
    return {
      // 添加搜索框显示状态
      showSearch: false,
      // 用户管理列表
      selUserListQuery: {
        page: 1,
        pageSize: 10,
        name: '',
        department: '',
        role: ''
      },
      // 添加用户表单
      addUserForm: {
        name: '',
        loginName: '',
        // password: "",
        mobile: '',
        departmentId: '',
        // email: "",
        roleId: []
      },
      // 角色列表
      selRoleListQuery: {
        page: 1,
        pageSize: 50
      },
      // 部门列表
      selDepartmentListQuery: {
        page: 1,
        pageSize: 10
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        realName: '',
        accountName: '',
        department: ''
      },
      // 表格数据
      tableData: [
        {
          accountName: '管理员',
          loginAccount: 'TVAdmin',
          role: '超级管理员',
          department: '',
          updateTime: '2025-01-21',
          createTime: '2017-04-06'
        },
        {
          accountName: '普通用户',
          loginAccount: 'user',
          role: '法律顾问',
          department: '行政中心',
          updateTime: '2024-10-18',
          createTime: '2022-10-27'
        }
      ],
      isFilterVisible: false,
      // 总条数
      total: 77,
      // 加载状态
      loading: false,
      // 对话框显示状态
      dialogVisible: false,
      // 添加密码可见性控制
      passwordVisible: false,
      // 表单对象
      formData: {
        id: '',
        name: '',
        loginName: '',
        password: '', // 添加 password 字段
        mobile: '',
        departmentId: null,
        roleId: []
      },
      // 总条数
      total: 0,
      // 用户列表
      selUserLists: [],
      selectedIds: [],
      rules: {
        name: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
        loginName: [
          { required: true, message: '请输入账户名称', trigger: 'blur' }
        ],
        password: [
          // {
          //   validator: (rule, value, callback) => {
          //     // 编辑时密码可以为空
          //     if (this.formData.id && !value) {
          //       callback();
          //       return;
          //     }
          //     // 新增时密码必填
          //     if (!this.formData.id && !value) {
          //       callback(new Error("请输入密码"));
          //       return;
          //     }
          //     // 密码格式验证
          //     if (value && value.length < 6) {
          //       callback(new Error("密码长度不能小于6位"));
          //       return;
          //     }
          //     callback();
          //   },
          //   trigger: "blur",
          // },
        ],
        mobile: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
        // departmentId: [
        //   {
        //     required: true,
        //     type: "number",
        //     message: "请选择所属部门",
        //     trigger: "change",
        //   },
        // ],
      },
      roleList: [] // 角色列表
    }
  },
  created() {
    this.selUserList()
    this.selRoleList()
    this.selDepartmentList()
  },
  methods: {
    // 切换搜索框显示状态
    // toggleSearch() {
    //   this.showSearch = !this.showSearch;
    // },
    // 用户管理列表
    async selUserList() {
      const res = await selUserListApi(this.selUserListQuery)
      console.log(res)
      this.selUserLists = res.records
      this.total = res.total
    },
    // 角色选择
    handleRoleChange(val) {
      console.log(val)
      this.selUserList()
    },
    // 获取角色列表
    async selRoleList() {
      try {
        const res = await selRoleListApi(this.selRoleListQuery)
        this.roleList = res.records || []
        console.log(this.roleList)
      } catch (error) {
        console.error('获取角色列表失败:', error)
        this.$message.error('获取角色列表失败')
      }
    },
    // 部门列表
    async selDepartmentList() {
      const res = await selDepartmentListApi(this.selDepartmentListQuery)
      this.departmentList = res.records || []
      console.log(this.departmentList)
    },
    // 批量删除
    handleDeleteClick() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请至少选择一个用户')
        return
      }
      this.$confirm('确认删除所选用户吗？', '提示', {
        type: 'warning'
      })
        .then(async() => {
          const res = await delUserByIdApi(this.selectedIds)
          console.log(res)
          this.$message.success('删除成功')
          this.selectedIds = []
          this.selUserList()
        })
        .catch(() => {})
    },
    // 关闭对话框
    close() {
      this.dialogVisible = false
      this.resetForm()
    },
    // 查询按钮点击事件
    handleQuery() {
      this.selUserListQuery.page = 1
      this.selUserList()
    },
    // 重置按钮点击事件
    resetQuery() {
      this.selUserListQuery = {
        page: 1,
        pageSize: 10,
        name: '',
        departmentId: '',
        roleId: ''
      }
      this.selUserList()
    },
    // 表格选择项变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
      this.selectedIds = selection.map((item) => item.id)
    },
    // 编辑按钮点击事件
    async handleEdit(row) {
      try {
        const res = await selUserByIdApi(row.id)
        if (res.code === 1) {
          // 处理返回的数据进行表单回显
          this.formData = {
            id: row.id,
            name: res.data.name,
            loginName: res.data.loginName,
            password: '', // 清空密码字段
            mobile: res.data.mobile || '',
            departmentId: res.data.departmentId,
            roleId: res.data.roleId || []
          }
          this.dialogVisible = true
        } else {
          this.$message.error(res.msg || '获取用户信息失败')
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.$message.error('获取用户信息失败')
      }
    },
    // 删除按钮点击事件
    handleDelete(row) {
      this.$confirm('确认删除该用户吗？', '提示', {
        type: 'warning'
      })
        .then(async() => {
          const res = await delUserByIdApi([row.id])
          console.log(res)
          this.$message.success('删除成功')
          this.selUserList()
        })
        .catch(() => {})
    },
    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate(async(valid) => {
        if (valid) {
          try {
            let res
            const params = { ...this.formData }
            console.log(this.formData)

            // // 如果是编辑且密码为空，则删除密码字段
            // if (this.formData.id && !this.formData.password) {
            //   delete params.password;
            // }

            if (this.formData.id) {
              res = await updateUserByIdApi(params)
            } else {
              res = await addUserApi(params)
            }

            if (res.code === 1) {
              this.$message.success(this.formData.id ? '编辑成功' : '新增成功')
              this.dialogVisible = false
              this.selUserList() // 刷新列表
            } else {
              this.$message.error(
                res.msg || (this.formData.id ? '编辑失败' : '新增失败')
              )
            }
          } catch (error) {
            console.error('操作失败:', error)
            this.$message.error('操作失败')
          }
        }
      })
    },
    // 格式化创建时间
    formatCreateTime(time) {
      if (!time) return ''
      // 找到第二个冒号的位置并截取字符串
      const secondColonIndex = time.indexOf(':', time.indexOf(':') + 1)
      return time.substring(0, secondColonIndex)
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.selUserListQuery.pageSize = val
      this.selUserList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.selUserListQuery.page = val
      this.selUserList()
    },
    // 部门选择
    handleDepartmentsChange(val) {
      console.log(val)
      this.selUserList()
    },
    // 重置表单
    resetForm() {
      this.formData = {
        id: '',
        name: '',
        loginName: '',
        password: '',
        mobile: '',
        departmentId: null,
        roleId: []
      }
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
    },
    // 处理部门选择
    handleDepartmentChange(value) {
      console.log(value)
      // this.formData.departmentId = Number(value);
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 16px;
}

/* 添加过渡动画样式 */
.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateY(-20px);
  opacity: 0;
}

.table-operations {
  margin-bottom: 16px;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.contract-number {
  font-size: 14px;
  color: #409eff;
  margin-bottom: 20px;
}

.left {
  display: flex;
  align-items: center;
}

.el-button + .el-button {
  margin-left: 8px;
}

.el-button--text {
  padding: 0 8px;
}

.role-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 4px;
  padding: 0;
}

:deep(.el-checkbox) {
  margin-right: 0;
  margin-left: 0;
  height: 24px;
  line-height: 24px;
}

:deep(.el-checkbox__label) {
  padding-left: 6px;
  font-size: 13px;
}

/* .dialog-footer {
  text-align: center;
} */

.dialog-footer .el-button {
  width: 80px;
  height: 32px;
  padding: 0;
}

:deep(.el-dialog__body) {
  padding: 15px 20px;
}

/* :deep(.el-select) {
  width: 100%;
} */

/* 确保所有 form-item 的标签都独占一行 */
:deep(.el-form-item) {
  /* margin-bottom: 10px; */
}

:deep(.el-form-item__label) {
  float: none !important; /* 添加 !important 确保覆盖默认样式 */
  display: block !important;
  text-align: left;
  padding: 0 0 4px 0;
  line-height: 20px;
  font-size: 14px;
  color: #606266;
  height: auto !important; /* 确保高度自适应 */
}

:deep(.el-form-item__content) {
  margin-left: 0 !important;
  line-height: normal;
}

/* 调整下拉框和输入框的样式 */
:deep(.el-select) {
  width: 100%;
  display: block; /* 确保select占满整行 */
}

:deep(.el-input__inner) {
  height: 32px;
  line-height: 32px;
}

/* 表单标签样式 */
.form-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
  line-height: 20px;
}

/* 必填项的红色星号 */
.form-label.required::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

/* 移除 form-item 的默认边距 */
:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-form-item__content) {
  margin-left: 0 !important;
  line-height: normal;
}

/* 确保下拉框和输入框样式一致 */
:deep(.el-select) {
  width: 100%;
  display: block;
}

:deep(.el-select .el-input) {
  width: 100%;
}

:deep(.el-select .el-input__inner) {
  height: 32px;
  line-height: 32px;
}

/* 调整行间距 */
.el-row {
  margin-bottom: 8px;
}

.el-row:last-child {
  margin-bottom: 0;
}

/* 专门处理 select 组件样式 */
:deep(.custom-select) {
  width: 100%;
}

:deep(.custom-select .el-input) {
  width: 100%;
}

:deep(.custom-select .el-input__inner) {
  width: 100%;
  height: 32px;
  line-height: 32px;
}

/* 确保 select 和 input 的容器宽度一致 */
:deep(.el-select),
:deep(.el-input) {
  width: 100%;
  display: block;
}

/* 调整错误提示的位置 */
:deep(.el-form-item__error) {
  padding-top: 2px;
  position: absolute;
}

/* 修改所属部门的表单项样式 */
:deep(.el-form-item) {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

:deep(.el-form-item__label) {
  float: none !important;
  display: block !important;
  text-align: left;
  padding: 0 0 4px 0;
  line-height: 20px;
  font-size: 14px;
  color: #606266;
  height: auto !important;
}

:deep(.el-form-item__content) {
  margin-left: 0 !important;
  width: 100%;
}

:deep(.el-select),
:deep(.el-input) {
  width: 100%;
}

/* 确保下拉框和输入框的高度一致 */
:deep(.el-input__inner) {
  height: 32px;
  line-height: 32px;
}

/* 添加密码可见性图标样式 */
.password-eye {
  cursor: pointer;
  color: #909399;
  font-size: 16px;
  margin-right: 8px;
}

.password-eye:hover {
  color: #409eff;
}

/* 确保输入框有足够空间显示图标 */
:deep(.el-input__inner) {
  padding-right: 35px;
}
</style>
